<?php
/**
 * 游戏操作 用户中心
 * Game/player 显示用户信息
 * Game/show  显示单个用户详细信息
 * Game/getout 付费日志
 * Game/getdownlin 帐户信息
 * Game/noticeinfo 游戏公告
 * Game/addnotice 游戏公告添加
 * Game/editnotice 游戏公告修改
 * Game/delnotice 游戏公告删去
 * Game/delnotice 游戏公告删去
 * Game/updateinfo 游戏更新信息
 * Game/addupdate 游戏更新添加
 * Game/editupdate 游戏更新修改
 * Game/delupdate 游戏更新删去
 */
namespace app\admin\controller;

use Request;
use Db;
class Game extends Base
{
    private $partitionid; //当前区id
    public function initialize()
    {
        parent::initialize();
        $this->partitionid = session('partitionid'); //别名：避免与控制名冲突
        if (empty($this->partitionid)) {return $this->error('参数错误,请先选择分区，然后再操作', 'Partition/index');}

    }

     public function index()
     {



/*
		$srcfile = fopen("username.txt", "r");
		$srcs=array();
		$i=0;
		//输出文本中所有的行，直到文件结束为止。
		while(!feof($srcfile))
		{
		 $srcs[$i]= fgets($srcfile);//fgets()函数从文件指针中读取一行
		 $i++;
		}
		fclose($srcfile);
		$srcs=array_filter($srcs);

*/







         //$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
         //return $this->fetch();
		 $str = file_get_contents("./srcData/gamemoneyadd.txt");
		 $str_encoding = mb_convert_encoding($str, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');//转换字符集（编码）
		 $array = explode("\r\n", $str_encoding);
		 $narr = [];


		$array = array_filter($array);
		foreach ($array as $k => $v)//遍历循环
		{
			  $narr[$k] = array_filter(explode("|", $v));
		}
		$narr=array_filter($narr);

//print_r($narr);
		 //$contents= explode(",",$content);//explode()函数以","为标识符进行拆分
     }

/**
 * 用户信息表
 * @return [type] [description]
 */
    public function player($search = '', $val = '', $searchdate = '')
    {
        return $this->showlist($search, $val, $searchdate);
    }

    public function ajaxplayer($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {
        $data  = $this->ajaxlist($search, $searchdate, $val, $page, $limit);
        $field = 'server_id,chrname,seedname,account,online,deleted,create_time,last_login_time,last_logout_time,last_login_ip,lv,exp,money,money_bind,vcoin,vcoin_bind,vip_level,reinlevel,job,gender,guildid,chatoff';
        /*
        玩家id 昵称 等级 职业 性别  vip等级 是否在线  最后登录时间 id  vip 创建时间
         */

        $count = CreateGameModel($data['uid'], 'game')->table('player')->where($data['where'])->count();
        $list  = CreateGameModel($data['uid'], 'game')->table('player')->field($field)->where($data['where'])->page($data['page'], $data['limit'])->order('server_id', 'desc')->select();
        foreach ($list as $k => $v) {
            if ($v['job'] == 100) {
                $job = '战士';
            } elseif ($v['job'] == 101) {
                $job = '法师';
            } else if ($v['job'] == 102) {
                $job = '道士';
            }

            $gender = ($v['gender'] == 200) ? '男' : '女';

            $list[$k]['userinfo'] = $v['chrname'] . '|' . $v['lv'] . '|' . $job . '|' . $gender;
            $list[$k]['lastip']   = $v['last_logout_time'] . '|' . $v['last_login_ip'];
			$list[$k]['job'] = $job;
            $list[$k]['gender'] = $gender;
        }
        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
        //return $this->ajaxlist($search, $searchdate, $val, 1, $limit, 'tab_consume');
    }

    public function show()
    {
        $id    = $this->request->has('id') ? $this->request->param('id') : 0;
        $field = 'server_id,chrname,seedname,account,online,deleted,create_time,last_login_time,last_logout_time,last_login_ip,lv,exp,money,money_bind,vcoin,vcoin_bind,vip_level,reinlevel,job,gender,guildid,chatoff';
        $info  = CreateGameModel($this->partitionid, 'game')->table('player')->field($field)->where('account', $id)->find();
        foreach ($info as $k => $v) {
            if ($info['job'] == 100) {
                $job = '战士';
            } elseif ($info['job'] == 101) {
                $job = '法师';
            } else if ($info['job'] == 102) {
                $job = '道士';
            }
            $info['job']    = $job;
            $info['gender'] = ($info['gender'] == 200) ? '男' : '女';
        }

        $this->assign([
            'info' => $info,
        ]);
        return $this->fetch();
    }

    public function getout()
    {
        $info = $this->cmd(Request::post('name'), 'getout');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getout', 'admin/Game/player');
    }

    public function getdownlin()
    {
        $info = $this->cmd(Request::post('name'), 'getdownlin');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getdownlin', 'admin/Game/player');
    }

    public function getnospeak()
    {
        $info = $this->cmd(Request::post('name'), 'getnospeak');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getnospeak', 'admin/Game/player');
    }

    public function getspeak()
    {
        $info = $this->cmd(Request::post('name'), 'getspeak');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getspeak', 'admin/Game/player');
    }

    public function getsealip()
    {
        $info = $this->cmd(Request::post('name'), 'getsealip');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getsealip', 'admin/Game/player');
    }

    public function getunsealip()
    {
        $info = $this->cmd(Request::post('name'), 'getunsealip');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getunsealip', 'admin/Game/player');
    }

	public function getsealuser()
    {
        $info = $this->cmd(Request::post('name'), 'getsealip');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getsealip', 'admin/Game/player');
    }

    public function getunsealuser()
    {
        $info = $this->cmd(Request::post('name'), 'getunsealip');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getunsealip', 'admin/Game/player');
    }

    public function getstealth()
    {
        $info = $this->cmd(Request::post('name'), 'getstealth');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getstealth', 'admin/Game/player');
    }

    public function getnostealth()
    {
        $info = $this->cmd(Request::post('name'), 'getnostealth');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getnostealth', 'admin/Game/player');
    }

    public function getgm()
    {
        $cmd = Request::post('cmd');
        $info = $this->cmd(Request::post('name'), 'getgm');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：getgm-'.$cmd, 'admin/Game/player');
    }

    public function getslelct()
    {
        $info = $this->cmd(Request::post('name'), 'getslelct');
        if (!$info['code']) {return $this->error($info['msg']);}
        return $this->success($info['msg'] . '提交参数为：name,getslelct', 'admin/Game/player');
    }

	/**
	 * 游戏命令操作过程
	 * @param  [type] $id   id
	 * @param  [type] $name
	 * @param  [type] $act  [description]
	 * @return [type]       [description]
	 */
    private function cmd($name, $act,$id = '')
    {

        if (!Request::isPost()) {return ['code' => 0, "cdata" => "", 'msg' => "请求错误"];}
        $act = $act ? $act : '';
        if (empty($name) || empty($act)) {
            return ['code' => 0, "cdata" => "", 'msg' => "参数错误"];
        }
        $data = [
            'name' => $name, //角色
            'type' => 6, //类型
            'cmd'  => $act, //命令
        ];
        $url = $this->partitionurl();
        if (!$url) {return ['code' => 0, "cdata" => "", 'msg' => "接口地址没有设置"];}

        $postinfo = request_post($url, $data);

        if (empty($postinfo)) {return ['code' => 0, "cdata" => "", 'msg' => "提交错误" . $postinfo];}

        $pos = json_decode($postinfo, true);
        if ($pos['code'] == 1) {
            $msg   = "操作成功";
            $cdata = $pos['code'];
        } else {
            $msg   = "操作失败,错误代码" . $pos['code'];
            $cdata = $pos['code'];
        }
        return ['code' => 1, "cdata" => $cdata, 'msg' => $msg];

    }
	/**
	 * 分区url
	 * @return [type] [description]
	 */
    private function partitionurl()
    {
        $id           = $this->partitionid;
        $partitionurl = Db::name('partition')->where([['status', '=', 1], ['id', '=', $id]])->value('http');
        if (empty($partitionurl)) {
            //$partitionurl = Db::name('partition')->where([['status','=',1],['id','=',$id]])->value('platform_id');
            $info         = Db::name('partition')->field("b.http as http")->alias('a')->join('platform b', 'a.platform_id = b.id', 'left')->where([['a.status', '=', 1], ['b.status', '=', 1]])->find();
            $partitionurl = $info['http'];
        }
		return $partitionurl ?? false;
		/*
        if (empty($partitionurl)) {
            return false;
        } else {
            return $partitionurl;
        }
		*/
    }
	/**
	 * 基础数据
	 * @param  string $search     [description]
	 * @param  string $val        [description]
	 * @param  string $id         [description]
	 * @param  string $searchdate [description]
	 * @return [type]             [description]
	 */
    private function showlist($search = '', $val = '', $searchdate = '', $von = '')
    {
        $id = $this->partitionid;
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        $search     = trim($search) ?? '';
        $val        = trim($val) ?? '';
        $searchdate = trim($searchdate) ?? '';
        //echo $searchdate;
        $this->assign([
            'id'         => $id,
            'search'     => $search,
            'val'        => $val,
            'searchdate' => $searchdate,
            'von'        => !empty($von) ? trim($von) : '',
        ]);
        return $this->fetch();
    }

    private function ajaxlist($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {
        $id = $this->partitionid;
        if (empty($id)) {return $this->error('参数错误');}
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        $where = [];

        $search     = trim($search) ?? '';
        $val        = trim($val) ?? '';
        $limit      = trim($limit) ?? config('webconfig.page');
        $searchdate = trim($searchdate) ?? '';

        if ($searchdate && $searchdate != '-') {
            $searchdate = explode(" - ", $searchdate);
            $where[]    = ['logtime', 'between', [$searchdate[0], $searchdate[1]]];
        }
        if ($search && $val) {
            if (preg_match("/[\x7f-\xff]/", $val)) {
                $where[] = [$search, 'like', '%' . $val . '%'];
            } else {
                $where[] = [$search, '=', $val];
            }
        }
        $page = !empty($page) ? $page : 1;

        return [
            'uid'   => $id,
            'where' => $where,
            'page'  => $page,
            'limit' => $limit,
        ];
    }

}
